<?php
declare (strict_types = 1);

namespace app\index\controller;

use app\index\BaseController;
use app\index\model\Article;
use app\index\model\Block;
use app\index\model\Tag as TagModel;
use think\facade\Log;

class Tag  extends BaseController
{
    //中间件
    protected $middleware = [
        'method:ajax' => ['only'=>['list']]
    ];

    //显示资源列表
    public function index()
    {
        return view('index',[
            'count'=> TagModel::getCount(),
            'limit'=> TagModel::LIMIT_NUM,

            'crumb' => [
                'home'=>'/',
                '标签列表' => request()->url()
            ]
        ]);
    }



    //显示指定的资源
    public function read(int $id)
    {
        $tag = $this->getModel(TagModel::class, $id);
        return view('read',[
            //文章列表
            'count' => Article::getCountByTag($id),
            'limit' => Article::LIMIT_NUM,


            'tag'   => $tag,
            'crumb' => [
                'home' => '/',
                '标签列表'  => (string) url('index'),
                $tag->name => request()->url()
            ],

            //*热门文章
            'activeArticles' => Block::getActiveArticles(),
            //*推荐话题
            'activeTopics' => Block::getActiveTopics(),
        ]);
    }

    //获取标签列表
    public function list()
    {
        try{
            //构建条件
            $where = [];

            //获取参数
            $name = input('name/s');
            if ($name){
                $where[] = ['name','like', '%'.$name.'%'];
            }

            //获取参数
            $page = input('page/d');
            $limit= input('limit/d');
            $data = TagModel::getList($page, $limit, $where);

            return json([
                'code' => 0,
                'data'  => $data
            ]);
        }catch (\Exception $e){
            //Log::error($e->getMessage());
            return json([
                'code' => 1,
                'msg'  => $e->getMessage()
            ]);
        }
    }



}
